package org.harlov.testsys.db;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.harlov.testsys.loger;

public class db_main {
		Connection dbh ;
	
	public db_main () throws ClassNotFoundException {
	try {
		Class.forName("org.postgresql.Driver");
		dbh = DriverManager.getConnection("jdbc:postgresql://ubuntu:5432/testbd","test","1991suse");
	} catch (SQLException e) {
		loger.add("Server connection:"+e.getMessage(),this, 1);
	}
	}
	
	public ResultSet makeReq (String requ) throws SQLException {
		
		Statement st = dbh.createStatement();		
		return st.executeQuery(requ);
	}
	
	public int makeUp (String requ) throws SQLException {
		Statement st = dbh.createStatement();
		return st.executeUpdate(requ);
	}
	
	public static String getMd5(String original) {
	String ret = null;
	try {
		MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
		digest.reset();
		digest.update(original.getBytes());
		byte messageDigest[] = digest.digest();
		
		StringBuffer hexString = new StringBuffer();
		for (int i=0;i<messageDigest.length;i++) {
			hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
		}
		ret = hexString.toString();
	}
	catch (NoSuchAlgorithmException e) {}
		return ret;
		
	}
	
	public static String makeParams (String[] parms) {
		StringBuilder ret = new StringBuilder("'");
		
		for (int i = 0; i<parms.length; i++) {
			if (i == parms.length-1) { 
				ret.append(parms[i]);
				ret.append("'");
			}
			else { 
				ret.append(parms[i]);
				ret.append("','");
			}
			
		}
		return ret.toString();
		
		
	}
	
	public static String makeArray(String[] elem) {
		StringBuilder ret = new StringBuilder("'{");
		for (int i = 0 ;i<elem.length; i++) {
			if (i == elem.length-1) {
				ret.append(elem[i]);
				ret.append("}'");
			}
			else {
				ret.append(elem[i]);
				ret.append(",");
			}
		}
		return ret.toString();
	}
	
	public static String makeArray(Boolean[] elem) {
		
		StringBuilder ret = new StringBuilder("'{");
		for (int i = 0 ;i<elem.length; i++) {
			if (i == elem.length-1) {
				ret.append(elem[i]);
				
				ret.append("}'");
			}
			else {
				ret.append(elem[i]);
				
				ret.append(",");
			}
		}
		return ret.toString();
	}
	
	public static String makeArray(int[] elem) {

		StringBuilder ret = new StringBuilder("'{");
		for (int i = 0 ;i<elem.length; i++) {
			if (i == elem.length-1) {
				ret.append(elem[i]);
				
				ret.append("}'");
			}
			else {
				ret.append(elem[i]);
				
				ret.append(",");
			}
		}
		return ret.toString();
	}
	

}
